import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _isEmpty from "lodash/isEmpty";

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _class, _class2;

/**
 * AuthorityManagement - 租户级权限维护
 * @date: 2018-7-31

 */
import React from 'react';
import { Form, Tabs, Spin, Card } from 'antd';
import { Bind } from 'lodash-decorators';
import { connect } from 'dva';
import { Button as ButtonPermission } from 'components/Permission';
import intl from 'utils/intl';
import formatterCollections from 'utils/intl/formatterCollections';
import { getCurrentOrganizationId } from 'utils/utils';
import notification from 'utils/notification';
import { loadDimensionAsync, hasDimension } from "../../../../customize/dimensions";
import Company from "./Detail/Company";
import AuthorityCopy from "./Detail/AuthorityCopy";
import AuthDetail from "../../../../components/AuthorityManagement/AuthDetail";
import DimensionTab from "../../../../components/AuthorityManagement";
import styles from "./index.less?modules";
var TabPane = Tabs.TabPane;
/**
 * 权限复制弹出框
 * @extends {Component} - React.Component
 * @reactProps {Object} roleId - 角色id
 * @reactProps {Object} copyModalVisible - 控制modal显示/隐藏属性
 * @reactProps {Function} refresh - 刷新数据
 * @reactProps {Function} authorityCopy - 控制modal显示隐藏方法
 * @reactProps {Object} organizationId - 组织编号
 * @return React.element
 */
// const AuthorityCopyModal = props => {
//   const { copyModalVisible, authorityCopy, roleId, organizationId, refresh } = props;
//   return (
//     <Modal
//       title={intl.get('ciam.authority.view.button.copy').d('权限复制')}
//       visible={copyModalVisible}
//       onCancel={() => {
//         authorityCopy(false);
//       }}
//       width={600}
//       footer={null}
//     >
//       <AuthorityCopy
//         authorityCopy={authorityCopy}
//         roleId={roleId}
//         organizationId={organizationId}
//         refresh={refresh}
//       />
//     </Modal>
//   );
// };
// /**
//  * 权限交换弹出框
//  * @extends {Component} - React.Component
//  * @reactProps {Object} changeModalVisible - 控制modal显示/隐藏属性
//  * @reactProps {Function} changeAuthority - 交换后触发方法
//  * @reactProps {Function} authorityChange - 控制modal显示隐藏方法
//  * @reactProps {Object} organizationId - 组织编号
//  * @return React.element
//  */
// const AuthorityChangeModal = Form.create({ fieldNameProp: null })(props => {
//   const {
//     changeModalVisible,
//     authorityChange,
//     changeAuthority,
//     organizationId,
//     form,
//     userId,
//   } = props;
//   return (
//     <Modal
//       title={intl
//         .get('ciam.authority.model.authorityManagement.authorityChange')
//         .d('权限交换')}
//       visible={changeModalVisible}
//       onOk={() => {
//         form.validateFields((err, fieldsValue) => {
//           if (!err) {
//             changeAuthority(fieldsValue, form);
//           }
//         });
//       }}
//       onCancel={() => {
//         authorityChange(false);
//       }}
//       width={500}
//     >
//       <div>
//         {intl
//           .get('ciam.authority.view.message.title.authorityChange')
//           .d('权限交换操作会将当前用户与所选用户权限值进行互换，请谨慎操作!')}
//       </div>
//       <React.Fragment>
//         <FormItem>
//           {form.getFieldDecorator('authorityChangeId')(
//             <Lov code="CIAM.USER_AUTHORITY_USER" queryParams={{ organizationId, userId }} />
//           )}
//         </FormItem>
//       </React.Fragment>
//     </Modal>
//   );
// });

var AuthorityManagement = (_dec = formatterCollections({
  code: ['ciam.authority', 'entity.company', 'entity.customer', 'entity.supplier']
}), _dec2 = Form.create({
  fieldNameProp: null
}), _dec3 = connect(function (_ref) {
  var roleDataAuthorityValueList = _ref.roleDataAuthorityValueList,
      roleDataAuthorityPurorg = _ref.roleDataAuthorityPurorg,
      roleDataAuthorityPuragent = _ref.roleDataAuthorityPuragent,
      roleDataAuthorityLovView = _ref.roleDataAuthorityLovView,
      roleDataAuthorityDataSource = _ref.roleDataAuthorityDataSource,
      roleDataAuthorityDataGroup = _ref.roleDataAuthorityDataGroup,
      loading = _ref.loading;
  return {
    roleDataAuthorityValueList: roleDataAuthorityValueList,
    addValueListLoading: loading.effects['roleDataAuthorityValueList/addAuthorityValueList'],
    fetchValueListLoading: loading.effects['roleDataAuthorityValueList/fetchAuthorityValueList'],
    roleDataAuthorityPurorg: roleDataAuthorityPurorg,
    addPurorgLoading: loading.effects['roleDataAuthorityPurorg/addAuthorityPurorg'],
    fetchPurorgLoading: loading.effects['roleDataAuthorityPurorg/fetchAuthorityPurorg'],
    roleDataAuthorityPuragent: roleDataAuthorityPuragent,
    addPuragentLoading: loading.effects['roleDataAuthorityPuragent/addAuthorityPuragent'],
    fetchPuragentLoading: loading.effects['roleDataAuthorityPuragent/fetchAuthorityPuragent'],
    roleDataAuthorityLovView: roleDataAuthorityLovView,
    addLovViewLoading: loading.effects['roleDataAuthorityLovView/addAuthorityLovView'],
    fetchLovViewLoading: loading.effects['roleDataAuthorityLovView/fetchAuthorityLovView'],
    roleDataAuthorityDataSource: roleDataAuthorityDataSource,
    addDataSourceLoading: loading.effects['roleDataAuthorityDataSource/addAuthorityDataSource'],
    fetchDataSourceLoading: loading.effects['roleDataAuthorityDataSource/fetchAuthorityDataSource'],
    roleDataAuthorityDataGroup: roleDataAuthorityDataGroup,
    addDataGroupLoading: loading.effects['roleDataAuthorityDataGroup/addAuthorityDataGroup'],
    fetchDataGroupLoading: loading.effects['roleDataAuthorityDataGroup/fetchAuthorityDataGroup']
  };
}), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), _dec8 = Bind(), _dec9 = Bind(), _dec(_class = _dec2(_class = _dec3(_class = (_class2 = /*#__PURE__*/function (_React$Component) {
  _inherits(AuthorityManagement, _React$Component);

  var _super = _createSuper(AuthorityManagement);

  function AuthorityManagement(props) {
    var _this;

    _classCallCheck(this, AuthorityManagement);

    _this = _super.call(this, props);
    var organizationId = getCurrentOrganizationId();
    _this.state = {
      userId: '',
      organizationId: organizationId,
      defaultList: [],
      copyModalVisible: false,
      // changeModalVisible: false,
      // tabList: ['company', 'purorg', 'puragent', 'lov', 'lovView', 'datasource', 'dataGroup'],
      tabList: []
    };
    return _this;
  }

  _createClass(AuthorityManagement, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this2 = this;

      var _this$props = this.props,
          dispatch = _this$props.dispatch,
          roleId = _this$props.roleId;
      this.renderDefaultTabs();
      dispatch({
        type: 'roleDataAuthorityManagement/fetchTabList',
        payload: {
          roleId: roleId
        }
      }).then(function (res) {
        if (!_isEmpty(res)) {
          var defaultList = ['PURORG', 'LOV', 'DATASOURCE', 'LOV_VIEW', 'PURAGENT', 'COMPANY', 'DATA_GROUP'];
          var arr = res.filter(function (item) {
            return defaultList.includes(item.valueSource) && item.valueSourceType === 'LOCAL';
          }).filter(function (item) {
            return !hasDimension(item);
          }).map(function (item) {
            return item.valueSource;
          });

          _this2.setState({
            defaultList: arr
          });

          _this2.loadDimensions(res);
        }
      });
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      var dispatch = this.props.dispatch; // TODO: 为了 清除缓存 需要在这里将所有model还原到初始化

      dispatch({
        type: 'roleDataAuthorityManagement/updateState',
        payload: {
          authorList: []
        }
      });
      dispatch({
        type: 'roleDataAuthorityCompany/updateState',
        payload: {
          data: [],
          checkList: [],
          originList: [],
          expandedRowKeys: []
        }
      });
      dispatch({
        type: 'roleDataAuthorityPuragent/updateState',
        payload: {
          head: {},
          // 头部数据
          list: [],
          // 请求查询到的数据
          pagination: {},
          // 分页信息
          puragentDataSource: [],
          puragentPagination: {}
        }
      });
      dispatch({
        type: 'roleDataAuthorityPurorg/updateState',
        payload: {
          head: {},
          // 头部数据
          list: [],
          // 请求查询到的数据
          pagination: {},
          // 分页信息
          purorgDataSource: [],
          purorgPagination: {}
        }
      });
      dispatch({
        type: 'roleDataAuthorityDataSource/updateState',
        payload: {
          head: {},
          // 头部数据
          list: [],
          // 请求查询到的数据
          pagination: {},
          // 分页信息
          createDataSource: [],
          createPagination: {}
        }
      });
      dispatch({
        type: 'roleDataAuthorityDataGroup/updateState',
        payload: {
          head: {},
          // 头部数据
          list: [],
          // 请求查询到的数据
          pagination: {},
          // 分页信息
          createDataSource: [],
          createPagination: {}
        }
      });
      dispatch({
        type: 'roleDataAuthorityValueList/updateState',
        payload: {
          head: {},
          // 头部数据
          list: [],
          // 请求查询到的数据
          pagination: {},
          // 分页信息
          createDataSource: [],
          createPagination: {}
        }
      });
    }
    /**
     * 加载单独的组件, 失败返回 失败的页面
     * @param {string} code - 维度编码
     * @return {React.Component|null}
     */

  }, {
    key: "importDimension",
    value: function () {
      var _importDimension = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(code) {
        var loadDimension;
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                loadDimension = null;
                _context.prev = 1;
                _context.next = 4;
                return loadDimensionAsync(code);

              case 4:
                loadDimension = _context.sent;
                _context.next = 10;
                break;

              case 7:
                _context.prev = 7;
                _context.t0 = _context["catch"](1);
                loadDimension = null;

              case 10:
                return _context.abrupt("return", loadDimension);

              case 11:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, null, [[1, 7]]);
      }));

      function importDimension(_x) {
        return _importDimension.apply(this, arguments);
      }

      return importDimension;
    }()
    /**
     * 加载所有的维度组件
     */

  }, {
    key: "importDimensions",
    value: function () {
      var _importDimensions = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
        var _this3 = this;

        var _len,
            dimensions,
            _key,
            _args2 = arguments;

        return _regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                for (_len = _args2.length, dimensions = new Array(_len), _key = 0; _key < _len; _key++) {
                  dimensions[_key] = _args2[_key];
                }

                return _context2.abrupt("return", Promise.all(dimensions.map(function (item) {
                  return _this3.importDimension(item.valueSource);
                })));

              case 2:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2);
      }));

      function importDimensions() {
        return _importDimensions.apply(this, arguments);
      }

      return importDimensions;
    }()
    /**
     * 将 卡片 加载成 layout
     */

  }, {
    key: "loadDimensions",
    value: function loadDimensions() {
      var _this4 = this;

      var layouts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
      var _this$props2 = this.props,
          roleId = _this$props2.roleId,
          tenantId = _this$props2.tenantId;
      var layout = layouts;
      var arr = [];
      var dimensions = [];
      this.importDimensions.apply(this, _toConsumableArray(layout)).then(function (cmps) {
        dimensions = layout.map(function (item, index) {
          var cmp = cmps[index];

          if (item.valueSourceType === 'LOV') {
            return {
              code: item.valueSource,
              name: item.dimensionName,
              valueSource: item.valueSource,
              component: /*#__PURE__*/React.createElement(DimensionTab, {
                code: item.viewCode,
                name: item.dimensionName,
                authorityTypeCode: item.dimensionCode,
                queryParams: {
                  roleId: roleId
                },
                tenantId: tenantId
              })
            };
          } else if (cmp) {
            arr.push(item.valueSource);

            if (cmp.__esModule) {
              var CpaasDimension = cmp.default;
              return {
                code: item.valueSource,
                name: item.dimensionName,
                component: /*#__PURE__*/React.createElement(CpaasDimension, {
                  dimensionParams: item,
                  tenantId: tenantId,
                  queryParams: {
                    roleId: roleId
                  }
                })
              };
            } else {
              var _CpaasDimension = cmp;
              return {
                code: item.valueSource,
                name: item.dimensionName,
                component: /*#__PURE__*/React.createElement(_CpaasDimension, {
                  dimensionParams: item,
                  tenantId: tenantId,
                  queryParams: {
                    roleId: roleId
                  }
                })
              };
            }
          } else {
            return {
              code: item.valueSource,
              name: item.dimensionName,
              component: /*#__PURE__*/React.createElement(Card, {
                loading: true
              })
            };
          }
        });
      }).finally(function () {
        var defaultList = _this4.state.defaultList;

        _this4.setState({
          dimensions: dimensions,
          defaultList: defaultList.filter(function (item) {
            return !arr.includes(item);
          })
        });
      });
    }
  }, {
    key: "renderDimensions",
    value: function renderDimensions() {
      var _this$state = this.state,
          _this$state$dimension = _this$state.dimensions,
          dimensions = _this$state$dimension === void 0 ? [] : _this$state$dimension,
          defaultList = _this$state.defaultList,
          tabList = _this$state.tabList;
      return dimensions.map(function (item) {
        if (!defaultList.includes(item.code)) {
          return /*#__PURE__*/React.createElement(TabPane, {
            tab: item.name,
            key: item.name
          }, item.component);
        } else {
          return /*#__PURE__*/React.createElement(TabPane, {
            tab: item.name,
            key: item.name
          }, tabList.find(function (temp) {
            return temp.code === item.code;
          }).component);
        }
      }).filter(function (item) {
        return !!item;
      });
    }
  }, {
    key: "renderDefaultTabs",
    value: function renderDefaultTabs() {
      var _this$props3 = this.props,
          _this$props3$dispatch = _this$props3.dispatch,
          dispatch = _this$props3$dispatch === void 0 ? function (e) {
        return e;
      } : _this$props3$dispatch,
          path = _this$props3.path,
          roleId = _this$props3.roleId;
      var organizationId = this.state.organizationId;
      var companyProps = {
        path: path,
        dispatch: dispatch,
        organizationId: organizationId,
        roleId: roleId
      }; // 采购组织

      var purorgProps = {
        code: 'purorg',
        name: intl.get('ciam.authority.view.message.tab.purorg').d('采购组织'),
        path: path,
        dispatch: dispatch,
        organizationId: organizationId,
        roleId: roleId
      };
      var puragentProps = {
        code: 'puragent',
        name: intl.get('ciam.authority.view.message.tab.puragent').d('采购员'),
        path: path,
        dispatch: dispatch,
        organizationId: organizationId,
        roleId: roleId
      };
      var valueListProps = {
        code: 'valueList',
        name: intl.get('ciam.authority.view.message.tab.valueList').d('值集'),
        path: path,
        dispatch: dispatch,
        organizationId: organizationId,
        roleId: roleId // roleDataAuthority: roleDataAuthorityValueList,
        // addLoading: addValueListLoading,
        // fetchLoading: fetchValueListLoading,

      };
      var lovViewProps = {
        code: 'lovView',
        name: intl.get('ciam.authority.view.message.tab.lovView').d('值集视图'),
        path: path,
        dispatch: dispatch,
        organizationId: organizationId,
        roleId: roleId
      }; // 数据源

      var dataSourceProps = {
        code: 'dataSource',
        name: intl.get('ciam.authority.view.message.tab.dataSource').d('数据源'),
        path: path,
        dispatch: dispatch,
        organizationId: organizationId,
        roleId: roleId
      }; // 数据组

      var dataGroupProps = {
        code: 'dataGroup',
        name: intl.get('ciam.authority.view.message.tab.dataGroup').d('数据组'),
        path: path,
        dispatch: dispatch,
        organizationId: organizationId,
        roleId: roleId
      };
      var tabList = [{
        code: 'COMPANY',
        component: /*#__PURE__*/React.createElement(Company, companyProps)
      }, {
        code: 'PURORG',
        component: /*#__PURE__*/React.createElement(AuthDetail, purorgProps)
      }, {
        code: 'PURAGENT',
        component: /*#__PURE__*/React.createElement(AuthDetail, puragentProps)
      }, {
        code: 'LOV',
        component: /*#__PURE__*/React.createElement(AuthDetail, valueListProps)
      }, {
        code: 'LOV_VIEW',
        component: /*#__PURE__*/React.createElement(AuthDetail, lovViewProps)
      }, {
        code: 'DATASOURCE',
        component: /*#__PURE__*/React.createElement(AuthDetail, dataSourceProps)
      }, {
        code: 'DATA_GROUP',
        component: /*#__PURE__*/React.createElement(AuthDetail, dataGroupProps)
      }];
      this.setState({
        tabList: tabList
      });
    }
    /**
     *刷新数据
     *
     */

  }, {
    key: "refresh",
    value: function refresh() {
      var _this$props4 = this.props,
          dispatch = _this$props4.dispatch,
          roleId = _this$props4.roleId;
      dispatch({
        type: 'roleDataAuthorityCompany/fetchAuthorityCompany',
        payload: {
          roleId: roleId
        }
      }); // this.setState({
      //   tabList: ['customer', 'purorg', 'puragent', 'lov', 'lovView', 'datasource', 'dataGroup'],
      // });
    }
    /**
     *权限交换modal显示隐藏标记
     *
     * @param {*Boolean} flag 隐藏/显示标记
     */
    // @Bind()
    // authorityChange(flag) {
    // this.setState({
    //   changeModalVisible: !!flag,
    // });
    // }

    /**
     *权限复制modal显示隐藏方法
     *
     * @param {Boolean} flag 隐藏/显示标记
     */

  }, {
    key: "authorityCopy",
    value: function authorityCopy(flag) {
      this.setState({
        copyModalVisible: !!flag
      });
    }
    /**
     *权限更改触发方法
     *
     * @param {Object} values form数据
     * @param {Object} form form表单
     */

  }, {
    key: "changeAuthority",
    value: function changeAuthority(values, form) {
      var _this5 = this;

      var dispatch = this.props.dispatch;
      var userId = this.state.userId;
      dispatch({
        type: 'authorityManagement/changeAuthority',
        payload: {
          userId: userId,
          exchanageUserId: values.authorityChangeId
        }
      }).then(function (response) {
        if (response) {
          notification.success();
          form.resetFields(); // this.authorityChange(false);

          _this5.refresh();
        }
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this6 = this;

      var _this$props5 = this.props,
          _this$props5$authorit = _this$props5.authorityManagement.authorList,
          authorList = _this$props5$authorit === void 0 ? [] : _this$props5$authorit,
          path = _this$props5.path,
          roleId = _this$props5.roleId,
          dispatch = _this$props5.dispatch,
          fetchTabListLoading = _this$props5.fetchTabListLoading;
      var copyModalVisible = this.state.copyModalVisible;
      return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
        style: {
          marginBottom: 16,
          textAlign: 'right'
        }
      }, /*#__PURE__*/React.createElement(ButtonPermission, {
        icon: "copy",
        type: "primary",
        style: {
          marginRight: 6
        },
        onClick: function onClick() {
          return _this6.authorityCopy(true);
        },
        permissionList: [{
          code: "".concat(path, ".button.copy"),
          type: 'button',
          meaning: '角色管理-角色复制'
        }]
      }, intl.get('ciam.authority.view.button.copy').d('权限复制'))), /*#__PURE__*/React.createElement("div", {
        style: {
          minHeight: '100px'
        }
      }, /*#__PURE__*/React.createElement(Spin, {
        spinning: fetchTabListLoading
      }, authorList.length > 0 && /*#__PURE__*/React.createElement(Tabs, {
        defaultActiveKey: "company",
        animated: false // onChange={this.tabChange}
        ,
        tabPosition: "left" // style={{ width: '150px',
        //   backgroundColor: '#f5f5f5' }}
        ,
        className: styles['sub-accout-tabs'],
        loading: fetchTabListLoading
      }, this.renderDimensions()), _isEmpty(authorList) && !fetchTabListLoading && /*#__PURE__*/React.createElement("h3", {
        style: {
          color: 'gray',
          marginTop: '10%',
          textAlign: 'center'
        }
      }, intl.get('ciam.authority.model.authorityManagement.noAuthority').d('当前暂无可维护的数据权限')))), /*#__PURE__*/React.createElement(AuthorityCopy, {
        dispatch: dispatch,
        visible: copyModalVisible,
        onCancel: this.authorityCopy,
        roleId: roleId,
        refresh: this.refresh,
        path: path
      }));
    }
  }]);

  return AuthorityManagement;
}(React.Component), (_applyDecoratedDescriptor(_class2.prototype, "loadDimensions", [_dec4], Object.getOwnPropertyDescriptor(_class2.prototype, "loadDimensions"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "renderDimensions", [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "renderDimensions"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "renderDefaultTabs", [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "renderDefaultTabs"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "refresh", [_dec7], Object.getOwnPropertyDescriptor(_class2.prototype, "refresh"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "authorityCopy", [_dec8], Object.getOwnPropertyDescriptor(_class2.prototype, "authorityCopy"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "changeAuthority", [_dec9], Object.getOwnPropertyDescriptor(_class2.prototype, "changeAuthority"), _class2.prototype)), _class2)) || _class) || _class) || _class);
export { AuthorityManagement as default };